package com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.repository;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.FlowExecutionQueryInfo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.User;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.task.FlowExecutionQueryVo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.FlowTaskQueryRepository;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.UserRepository;
import com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.mapper.FlowExecutionQueryDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 * @author lilh
 * @date 2020/11/6 10:52
 */
@Repository
public class FlowTaskQueryRepositoryImpl implements FlowTaskQueryRepository {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private FlowExecutionQueryDAO flowExecutionQueryDAO;

    @Override
    public List<FlowExecutionQueryInfo> todoTasks(FlowExecutionQueryVo flowExecutionQueryVo) {
        List<FlowExecutionQueryInfo> flowExecutionQueryInfos = new ArrayList<>();
        User user = userRepository.getUserWithOrgByCode(flowExecutionQueryVo.getAssignee());
        if (Objects.isNull(user)) {
            return flowExecutionQueryInfos;
        }
        flowExecutionQueryVo.setAssignee(user.getUserCode());
        flowExecutionQueryVo.setCandidateUser(user.getUserCode());
        if (Objects.nonNull(user.getOrgCode())) {
            String[] split = user.getOrgCode().split(",");
            flowExecutionQueryVo.setCandidateGroup(Arrays.asList(split));
        }
        flowExecutionQueryVo.setPageNum(null);
        flowExecutionQueryVo.setPageSize(null);
        flowExecutionQueryInfos = flowExecutionQueryDAO.todoTasks(flowExecutionQueryVo);
        return flowExecutionQueryInfos;
    }

    @Override
    public List<FlowExecutionQueryInfo> historyTasks(FlowExecutionQueryVo flowExecutionQueryVo) {
        User user = userRepository.getUserWithOrgByCode(flowExecutionQueryVo.getAssignee());
        flowExecutionQueryVo.setAssignee(user.getUserCode());
        flowExecutionQueryVo.setPageNum(null);
        flowExecutionQueryVo.setPageSize(null);
        List<FlowExecutionQueryInfo> flowExecutionQueryInfos = flowExecutionQueryDAO.processedProcessInstance(flowExecutionQueryVo);
        return flowExecutionQueryInfos;
    }
}
